import {Component, ViewChild, NgZone, ChangeDetectorRef,} from '@angular/core';
import {IonicPage, NavController, NavParams, Content, Platform, ToastController} from 'ionic-angular';
import * as moment from 'moment';

import {ClientFilterProvider} from '../../../providers/client/client-filter/client-filter.provider';
import {
    Mate,
    PageData,
    Condition,
    ExportClient,
    FilterResponse
} from '../../../model/pages/client/client-filter/client-filter.model';
import {HolderClientDetailProvider} from '../../../providers/client/holder-client-detail/holder-client-detail.provider';
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {DateService} from '../../../services/common/date.service';

@IonicPage()
@Component({
    selector: 'page-client-filter',
    templateUrl: 'client-filter.html',
    providers: [
        ClientFilterProvider,
        HolderClientDetailProvider,
        ClientNoteEditProvider,
        DateService
    ]
})
export class ClientFilterPage extends InfiniteScrollModel {
    @ViewChild(Content) content: Content;
    // 时间插件--月汉字填充
    private monthOptions = {
        cssClass: 'month-picker'
    };
    // 筛选页面状态：筛选时、筛选完成时
    private pageStatus: number = 1;
    // 客户类型选择对象
    private clientType: any[] = ['O'];
    // VIP等级选择对象
    private levelType: any[] = [];
    // 性别选择对象
    private genderType: any[] = [];
    // 保单状态选择对象
    private policyType: any[] = [];
    // 时间插件--年月日汉字填充
    private pickerOptions = {
        cssClass: 'filter-add-picker'
    };
    // 主险产品类型
    private productType: any[] = [];
    // 年龄
    private age: Mate = new Mate();
    // 年缴保费
    private totlePrem: Mate = new Mate();
    // 理赔金额
    private claimAmt: Mate = new Mate();
    // 接力单时间
    private orphanDate: Mate = new Mate();
    // 生日范围
    private birth: Mate = new Mate();
    // 生日范围选择备份
    private copyBirth: Mate = new Mate();
    // 上次投保时间
    private lastSignDate: Mate = new Mate();
    // 理赔通过时间
    private claimDate: Mate = new Mate();
    // 客户筛选输入
    private condition: Condition = new Condition();
    // 客户筛选输出
    private exportClient: ExportClient[] = [];
    // 筛选响应
    private filterResponse: FilterResponse = new FilterResponse();

    // 当前分页索引
    private currentPage: number = 0;
    // 标注是否有成功筛选的经历
    private getDataStatus: boolean = false;
    // 底部按钮显示状态
    private footerStatus: boolean = true;
    // 页面重构数据
    private pageData: PageData = new PageData();
    // 返回键
    private backButtonHandle = () => this.backToProPage();
    // 聚焦状态
    private focusStatus: boolean = false;
    private isOrphanFlag: boolean = false;
    //展开主险名称
    private isClosed: boolean = false;
    //验证器
    private validator = {
        age: {
            hasError: false,
            validateFn: () => {
                if (this.age.to && this.age.from) {
                    return Number(this.age.from) <= Number(this.age.to);
                }
                return true;
            },
            message: '客户年龄输入有误'
        },
        claimAmt: {
            hasError: false,
            validateFn: () => {
                if (this.claimAmt.to && this.claimAmt.from) {
                    return Number(this.claimAmt.from) <= Number(this.claimAmt.to);
                }
                return true;
            },
            message: '理赔金额范围输入有误'
        },
        totlePrem: {
            hasError: false,
            validateFn: () => {
                if (this.totlePrem.to && this.totlePrem.from) {
                    return Number(this.totlePrem.from) <= Number(this.totlePrem.to);
                }
                return true;
            },
            message: '年缴保费范围输入有误'
        },
        birth: {
            hasError: false,
            validateFn: () => {
                if (this.condition.birthdayFrom && this.condition.birthdayTo) {
                    return true;
                } else if (!this.condition.birthdayFrom && !this.condition.birthdayTo) {
                    return true;
                } else {
                    return false;
                }
            },
            message: '请选择完整生日范围或不填'
        },
        orphanDate: {
            hasError: false,
            validateFn: () => {
                if (this.orphanDate.to && this.orphanDate.from) {
                    return new Date(this.orphanDate.from) <= new Date(this.orphanDate.to);
                }
                return true;
            },
            message: '成为接力单的时间输入有误'
        },
        lastSignDate: {
            hasError: false,
            validateFn: () => {
                if (this.lastSignDate.to && this.lastSignDate.from) {
                    return new Date(this.lastSignDate.from) <= new Date(this.lastSignDate.to);
                }
                return true;
            },
            message: '上次投保生效时间输入有误'
        },
        claimDate: {
            hasError: false,
            validateFn: () => {
                if (this.claimDate.to && this.claimDate.from) {
                    return new Date(this.claimDate.from) <= new Date(this.claimDate.to);
                }
                return true;
            },
            message: '理赔通过时间输入有误'
        }
    };

    //可否提交，默认可以
    private canSubmit: boolean = true;

    private isiPhoneX = false;
    private isiPhone5s = false;
    // 年度列表
    private yearList:any[]=[];

    constructor(public zone: NgZone,
                public navCtrl: NavController,
                public navParams: NavParams,
                public platform: Platform,
                public clientFilterProvider: ClientFilterProvider,
                public holderClientDetailProvider: HolderClientDetailProvider,
                public clientNoteEditProvider: ClientNoteEditProvider,
                public toastCtrl: ToastController,
                public dateService:DateService,
                public changeDetectorRef:ChangeDetectorRef,
                ) {
        super();
        this.yearList=this.dateService.getYearList(1900);
    }

    ionViewDidLoad() {
        this.birth.from = 2;
        if (this.platform.is('ios')) {
            let datetimes = document.querySelectorAll('ion-datetime');
            Array.prototype.forEach.call(datetimes, (el) => {
                el.addEventListener('click', () => {
                    this.content.scrollTo(0, this.content.scrollTop + 1);
                });
            });
        }
        this.isiPhoneX = /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375);
        this.isiPhone5s = /iphone/gi.test(navigator.userAgent) && screen.height == 568 && screen.width == 320;
    }

    ionViewWillLeave() {
        //this.footerStatus=false;
        this.content.scrollToTop();
    }

    ionViewDidEnter() {
        this.footerStatus = true;
    }

    /**
     * 选择客户、VIP、保单状态、类型
     * @param {number} num
     * @param {number[]} arr
     */
    selectType(num: number, arr: number[]) {
        let status = false, index = 0;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] == num) {
                index = i;
                status = true;
            }
        }
        if (status) {
            arr.splice(index, 1);
        } else {
            arr.push(num);
        }
        this.changeDetectorRef.detectChanges();
    }

    /**
     * 数组转化字符串并验证
     * @param {number} num
     * @param {number[]} arr
     * @returns {boolean}
     */
    testSelectItem(num: number, arr: number[]) {
        let str = arr.join('');
        return str.indexOf(String(num)) > -1;
    }

    /**
     * 生日选择
     * @param $event
     * @param {number} num
     */
    monthSelect($event, num: number) {
        if (num == 1) {
            this.condition.birthdayFrom = $event['month'];
        } else {
            this.condition.birthdayTo = $event['month'];
        }
        if (this.validator.birth.validateFn()) {
            this.validator.birth.hasError = false;
        }
        this.computeCanSubmit();
    }

    validateForm(key, ev) {
        if (this.platform.is('ios')) {
            this.focusStatus = false;
        }
        if (!this.validator[key].validateFn()) {
            this.validator[key].hasError = true;
            this.toastCtrl.create({
                message: this.validator[key].message,
                duration: 1500,
                position: 'middle'
            }).present();
        } else {
            this.validator[key].hasError = false;
        }
        this.computeCanSubmit();
    }


    // 确定筛选前修整数据
    buildData() {
        // 分页大小
        this.condition.pageSize = 20;
        // 客户类型
        this.condition.linkType = this.clientType.join(',') ? this.clientType.join(',') : null;
        // vip等级
        this.condition.vipFlag = this.levelType.join(',') ? this.levelType.join(',') : null;
        // 产品
        this.condition.productCode = this.productType.join(',').trim() ? this.productType.join(',').trim() : null;
        let other = '#CCC,CDC,CEC,CFC';
        let showArr = ['CCC', 'CDC', 'CEC', 'CFC'];
        let index = this.productType.indexOf(other);
        if (index !== -1 && this.productType.length > 1) {
            this.productType.forEach((item) => {
                if(item !== other) {
                    let index = showArr.findIndex((innerItem) => {
                        return innerItem === item;
                    });
                    showArr.splice(index, 1);
                }
            });
            if (showArr.length === 0) {
                this.condition.productCode = null;
            } else {
                this.condition.productCode = '#' + showArr.join(',');
            }
        } else {
            this.condition.productCode = this.productType.join(',').trim() ? this.productType.join(',').trim() : null;
        }

        // 年龄
        this.condition.ageFrom = this.age.from ? String(this.age.from) : null;
        this.condition.ageTo = this.age.to ? String(this.age.to) : null;

        // 年缴保费
        this.condition.totalPremFrom = this.totlePrem.from ? String(this.totlePrem.from) : null;
        this.condition.totalPremTo = this.totlePrem.to ? String(this.totlePrem.to) : null;

        // 理赔金额
        this.condition.claimAmtFrom = this.claimAmt.from ? String(this.claimAmt.from) : null;
        this.condition.claimAmtTo = this.claimAmt.to ? String(this.claimAmt.to) : null;

        // 性别
        this.condition.sexCode = this.genderType.join(',') ? this.genderType.join(',') : null;

        //是否是接力单
        this.condition.isOrphanFlag = this.isOrphanFlag ? 'Y' : null;
        // 接力单时间
        this.condition.orphanPolicyDateFrom = this.orphanDate.from ? moment(new Date(this.orphanDate.from)).startOf('day').unix() : null;
        this.condition.orphanPolicyDateTo = this.orphanDate.to ? moment(new Date(this.orphanDate.to)).endOf('day').unix() : null;
        // 上次投保时间
        this.condition.lastSignDateFrom = this.lastSignDate.from ? moment(new Date(this.lastSignDate.from)).startOf('day').unix() : null;
        this.condition.lastSignDateTo = this.lastSignDate.to ? moment(new Date(this.lastSignDate.to)).endOf('day').unix() : null;
        // 理赔通过时间
        this.condition.claimDateFrom = this.claimDate.from ? moment(new Date(this.claimDate.from)).startOf('day').unix() : null;
        this.condition.claimDateTo = this.claimDate.to ? moment(new Date(this.claimDate.to)).endOf('day').unix() : null;
        // 保单状态
        this.condition.policyStatus = this.policyType.join(',') ? this.policyType.join(',') : null;
    }

    // 重置数据
    cleanData() {
        // 客户类型
        this.clientType = ['O'];
        // vip等级
        this.levelType = [];

        // 主险产品类型
        this.productType = [];
        // 年龄
        this.age.from = null;
        this.age.to = null;

        // 年缴保费
        this.totlePrem.from = null;
        this.totlePrem.to = null;

        // 理赔金额
        this.claimAmt.from = null;
        this.claimAmt.to = null;

        // 性别
        this.genderType = [];

        // 生日
        this.birth.from = null;
        this.birth.to = null;
        this.condition.birthdayFrom = null;
        this.condition.birthdayTo = null;

        this.isOrphanFlag = false;
        // 接力单时间
        this.orphanDate.from = '';
        this.orphanDate.to = '';

        // 生日范围
        this.birth.from = null;
        this.birth.to = null;

        // 上次投保时间
        this.lastSignDate.from = '';
        this.lastSignDate.to = '';

        // 理赔通过时间
        this.claimDate.from = '';
        this.claimDate.to = '';

        // 保单状态
        this.policyType = [];

        this.canSubmit = true;
    }

    // 重置序列化数据
    cleanParams() {
        for (let item in this.condition) {
            if (item == 'linkType' || 'vipFlag' || 'sexCode' || 'policyStatus') {
                this.condition[item] = ''
            } else {
                this.condition[item] = null;
            }
        }
    }

    // 页面数据重构
    buildData1() {
        for (let item in this.pageData) {
            console.log(this.pageData[item] instanceof Array)
            if (this.pageData[item] instanceof Array) {
                this.condition[item] = this.pageData[item].join(',') ? this.pageData[item].join(',') : null;
            } else {
                let from = item + 'From', to = item + 'To';
                if (item == 'age' || 'totlePrem' || 'claimAmt') {
                    this.condition[from] = this.pageData[item]['from'] ? this.pageData[item]['from'] : null;
                    this.condition[to] = this.pageData[item]['to'] ? this.pageData[item]['to'] : null;
                } else {
                    this.condition[from] = this.pageData[item]['from'] ? moment(new Date(this.pageData[item]['from'])).unix() : null;
                    this.condition[to] = this.pageData[item]['to'] ? moment(new Date(this.pageData[item]['to'])).unix() : null;
                }
            }
        }
    }

    // 页面重构反解
    inverseData1() {
        for (let item in this.condition) {
            let from = item.indexOf('From') ? item.replace('From', '') : '';
            let to = item.indexOf('To') ? item.replace('To', '') : '';
            if (item == 'linkType' || 'vipFlag' || 'productCode' || 'policyStatus' || 'sexCode') {
                this.pageData[item] = this.condition[item] ? Number(this.condition[item]) : null;
            } else if (item == 'orphanPolicyDateFrom' || 'orphanPolicyDateTo' || 'lastSignDateFrom' || 'lastSignDateTo' || 'claimDateFrom' || 'claimDateTo') {
                if (from) {
                    this.pageData[from]['from'] = this.condition[item] ? moment(new Date(this.condition[item])).toISOString() : '';
                }
                if (to) {
                    this.pageData[to]['to'] = this.condition[item] ? moment(new Date(this.condition[item])).toISOString() : '';
                }
            } else {
                if (from) {
                    this.pageData[from]['from'] = this.condition[item] ? this.condition[item].split(',') : [];
                }
                if (to) {
                    this.pageData[to]['to'] = this.condition[item] ? this.condition[item].split(',') : [];
                }
            }
        }
    }

    // 页面重构重置序列化
    cleanParams1() {
        for (let item in this.pageData) {
            if (this.pageData[item] instanceof Array) {
                this.pageData[item] = [];
            } else if (item == 'age' || 'totalPrem' || 'claimAmt') {
                this.pageData[item]['from'] = null;
                this.pageData[item]['to'] = null;
            } else {
                this.pageData[item]['from'] = '';
                this.pageData[item]['to'] = null;
            }
        }
    }

    // 确定筛选
    filterHandler() {
        this.validateForm('birth', null);
        if (!this.validator.birth.validateFn()) {
            return;
        }
        this.buildData();
        this.copyBirth.from = this.condition.birthdayFrom;
        this.copyBirth.to = this.condition.birthdayTo;
        if (this.condition.linkType === 'I') {
            this.condition.vipFlag = null;
        }
        this.navCtrl.push('ClientFilterListPage', {
            data: this.condition,
            callback: this.callbak
        })
    }

    //计算可否提交
    computeCanSubmit() {
        let val = true;
        for (let o in this.validator) {
            val = val && !this.validator[o].hasError;
        }
        this.canSubmit = val;
    }

    // 传递回调
    callbak = (param) => {
        return new Promise((reslove, reject) => {
            if (param) {
                this.condition = param;
                this.footerStatus = true;
                console.log(this.condition)
                reslove();
            } else {
                reject();
            }
        })
    };

    // 重置数据
    resetData() {
        for (let o in this.validator) {
            this.validator[o].hasError = false;
        }
        this.cleanData();
    }

    // 取消筛选
    cancelFilter() {
        this.pageStatus = 2;
    }

    /**
     * 筛选请求
     * @param {number} pageNum
     * @param {number} pageSize
     * @param {string} orderType
     * @param {string} orderName
     * @param {Condition} condition
     */
    getFilterData(condition: Condition, fresh: boolean) {
        for (let o in this.validator) {
            if (this.validator[o].hasError) {
                this.toastCtrl.create({
                    message: '输入查询条件有误',
                    duration: 1500,
                    position: 'middle',
                }).present();
                return;
            }
        }
        this.clientFilterProvider.getClientFilter(condition).subscribe((res) => {
            this.filterResponse = res;
            if (fresh) {
                this.exportClient.concat(this.filterResponse.list);
            } else {
                this.exportClient = this.filterResponse.list;
            }
        })
    }


    // 到客户详情
    goToClientDetail(role, id) {
        const clientRole = role;
        /*if (role == 'O') {
            this.navCtrl.push('HolderClientDetailPage', {
                clientNum: id,
                role: clientRole
            })
        } else if (role == 'IO') {
            this.navCtrl.push('HolderClientDetailPage', {
                clientNum: id,
                role: clientRole
            })
        } else {
            this.navCtrl.push('InsuredClientDetailPage', {
                clientNum: id,
                role: clientRole
            })
        }*/
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: id,
            role: clientRole
        })
    }

    /**
     *  返回
     */
    backToProPage() {
        this.navCtrl.pop(null);
    }

    // input聚焦时content滚动
    scrollTo($event, id: string) {
        console.log($event.target.offsetParent.offsetParent.offsetParent.offsetParent);
        const top = $event.target.offsetParent.offsetParent.offsetParent.offsetTop;
        if (this.platform.is('ios')) {
            this.zone.run(() => {
                this.content.scrollTo(0, top);
            });
            this.focusStatus = true;
        } else {
            setTimeout(() => {
                this.content.scrollTo(0, top);
            }, 500);
        }
    }

    // 文本框失去焦点
    blurTo() {
        if (this.platform.is('ios')) {
            this.focusStatus = false;
        }
    }


    isShowVip() {
        if (this.clientType.length === 1 && this.clientType.indexOf('I') !== -1) {
            return false;
        }
        return true;
    }

    correctFloat($event, key1, key2) {
        let val = $event.value.replace(/[^\d|.]/ig, '');
        //去掉首位小数点

        val = val.replace(/^[.]+/, '');

        //去掉不合法的首位
        if (val.length > 1 && val.indexOf('0') === 0 && val.indexOf('.') !== 1) {
            val = val.replace(/^[0]+/, '');
        }

        //去掉第二个小数点
        if (this.countNum(val, '.') > 1) {
            let arr = val.split('');
            if (arr[arr.length - 1] === '.') {
                val = arr.slice(0, arr.length - 1).join();
            }
        }

        //保证两位小数
        if (this.countNum(val, '.') === 1) {
            let arr = val.split('.');
            val = arr[0] + '.' + arr[1].split('').splice(0, 2).join('');
        }

        $event.value = val;
        this[key1][key2] = val;
    }


    correct3Integer($event, key1, key2) {
        let val = $event.value.replace(/[^0-9]/ig, '');
        if ($event.value.length > 1) {
            val = val.replace(/^[0]+/, '');
        }
        let arr = val.split('');
        val = arr.splice(0, 3).join('');
        $event.value = val;
        this[key1][key2] = val;
    }

    correctInteger($event, key1, key2) {
        let val = $event.value.replace(/[^0-9]/ig, '');
        if ($event.value.length > 1) {
            val = val.replace(/^[0]+/, '');
        }
        $event.value = val;
        this[key1][key2] = val;
    }

    /**
     * 计算字符串中各个字符出现的次数
     * @param str
     */
    countNum(str, key) {
        let obj = {};
        str.split('').sort().join('').replace(/(.)(\1+)?/g, (m, k) => {
            obj[k] = m.length;
        });
        return obj[key];
    }

    cleanDateProp(key1, key2) {
        this[key1].to = this[key1].from = '';
        // this[key2].to = this[key2].from = {
        //     from: '1900-01-01',
        //     to: '2100-01-01'
        // };
    }

    cleanProp(key) {
        this[key].to = this[key].from = '';
    }

    cleanAge() {
        this.condition.birthdayFrom = this.condition.birthdayTo = null;
        this.birth.to = this.birth.from = null;
    }

    checkFlag () {
        if (!this.isOrphanFlag) {
            // 接力单时间
            this.orphanDate.from = '';
            this.orphanDate.to = '';
            this.validateForm('orphanDate', null);
        }
    }
}
